package math2.delaunay;

import fem2.Face;
import fem2.Mesh;
import fem2.Node;
import inf.v3d.obj.Object3D;
import inf.v3d.obj.PolygonSet;
import inf.v3d.view.Viewer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class AbstractDelaunay {

	private PolygonSet ps;

	public void addPoint(double x, double y) {
		this.addPoint(new Point(x, y));
	}

	public abstract void addPoint(Point p);

	public abstract List<Point> getPoints();

	public abstract List<Triangle> getTriangles();

	public void plot(Viewer v) {
		if (this.ps == null) {
			this.ps = new PolygonSet();
			ps.setColorMode(Object3D.CM_UNI);
			ps.setOutlinesVisible(true);
			ps.setColoringByData(true);
			v.addObject3D(ps);
		} else {
			this.ps.clear();
		}

		for (Triangle t : getTriangles()) {
			Point[] pts = t.getPoints();

			for (int i = 0; i < pts.length; i++) {
				ps.insertVertex(pts[i].toArray(), t.getAngle(i));
			}
			ps.polygonComplete();
		}
		ps.createColors();
	}

	public Mesh getMesh() {
		Mesh mesh = new Mesh();

		Map<Point, Node> map = new HashMap<Point, Node>();

		for (int i = 0; i < getPoints().size(); i++) {
			Point p = getPoints().get(i);
			Node n = new Node(p.getCoordinate());
			map.put(p, n);
			mesh.addNode(n);
		}

		for (Triangle t : getTriangles()) {
			mesh.addFace(new Face(map.get(t.getPi()), map.get(t.getPj()), map.get(t.getPk())));
		}

		return mesh;
	}
}
